import type { PipelineStage } from 'mongoose';
import { ActivityModel } from '@/database/schemas/activity.schema';
import { ActivityUsersModel } from '@/database/models/activityUsers.model';
import { joinTableQueryUser, joinTableQueryImage } from '@/database/filters/jointTable';
import { PhotoStatus } from '@/enums/photoEnums';

import type {
  ActivityDetail
} from '@/typings/activity';

import type {
  CreateActivityParams,
  GetActivitiesParams,
  ParticipateActivityParams
} from './types/activity.types';

export class ActivityService {
  /**
   * 获取活动详情
  */
  static getActivityById = async (id: string) => {
    const result = await ActivityModel.findById<ActivityDetail>(id).exec();
    return result as ActivityDetail;
  }

  /**
   * 创建一个活动
  */
  static createNewActivity = async (params: CreateActivityParams) => {
    const activity = new ActivityModel(params);
    const result = await activity.save();
    return result.toObject<ActivityDetail>();
  }

  /**
   * 获取活动列表
  */
  static getActivities = async (params: GetActivitiesParams) => {
    const { page = 1, pageSize = 10} = params;
    const skipCount = (page - 1) * pageSize;

    const pipeline: PipelineStage[] = [
      // 联表查询关联用户
      joinTableQueryUser('creator'),
      // 联表查询关联的图片
      joinTableQueryImage('images', [
        {
          $match: {
            status: {
              // 图片状态包含未审核和启用
              $in: [
                PhotoStatus.enable,
                PhotoStatus.unreviewed
              ]
            }
          }
        }
      ]),
      { $unwind: '$creator' },
      // ...filters,
      { $skip: skipCount },
      { $limit: pageSize }
    ];

    const result = await ActivityModel.aggregate(pipeline).exec();
    return result as ActivityDetail[];
  }

  /**
   * 用户参与一个活动
   * @userId 参与人userID
   * @activityId 活动ID
  */
  static userParticipateActivity = async (params: ParticipateActivityParams) => {
    const activityUser = new ActivityUsersModel({
      user: params.userId,
      activity: params.activityId
    });
    const result = await activityUser.save();
    return result;
  }

  // 检查当前用户已参与该活动
  static checkUserParticipated = async (params: ParticipateActivityParams) => {
    const result = await ActivityUsersModel.findOne({
      activity: params.activityId,
      user: params.userId
    })
    return !!result;
  }

  // 根据活动id获取参与记录
  static getParticipateRecordByActivityId = async (activityId: string) => {
    const result = await ActivityUsersModel.aggregate([
      {
        $match: {
          activity: activityId
        }
      },
      joinTableQueryUser('user'),
      { $unwind: '$user' },
    ]).exec()
    return result;
  }
}